// 导入数据库
const db = require('../db/index')
    // 导入bcryptjs加密密码
const bcryptjs = require('bcryptjs')
const config = require('../config')
const jwt = require('jsonwebtoken')
    // 注册路由的处理函数
exports.reg = (req, res) => {
        // 对数据验证
        const sql = `select * from stu_users where username=?`
        db.query(sql, req.body.username, (err, results) => {
            //sql错误信息
            if (err) return res.sd(err.message)
            if (results.length !== 0) return res.sd('用户名已注册')
                //加密密码
            const pwd = bcryptjs.hashSync(req.body.password, 5)
            const sql = `insert into stu_users set?`
            db.query(sql, { username: req.body.username, password: pwd }, (err, results) => {
                if (err) return res.send({
                        status: 1,
                        message: err.message
                    })
                    //通过是否影响行数判断是否添加成功
                if (results.affectedRows !== 1) return res.send({
                    status: 1,
                    message: '用户注册失败！'
                })
                res.send({
                    status: 0,
                    message: '用户注册成功！'
                })
            })
        })
    }
    //登录路由的处理函数
exports.login = (req, res) => {
    const sql = `select * from stu_users where username=?`
    db.query(sql, req.body.username, (err, results) => {
        if (err) return res.sd(err.message)
        if (results.length !== 1) return res.sd('登录失败11')
        const compareRes = bcryptjs.compareSync(req.body.password, results[0].password)
        if (!compareRes) return res.sd('登录失败22')
            // 删除头像和密码后的用户信息
        const { password, avater, ...user } = results[0]
        const tokenStr = jwt.sign(user, config.jwtSecretKey, {
            // 配置token的有效时长
            expiresIn: '24h'
        })
        res.send({
            status: 0,
            message: '登录成功',
            token: 'Bearer ' + tokenStr
        })
    })
}